package cn.example.practice.servlet;


import cn.example.practice.db.GoodsDao;
import cn.example.practice.model.Goods;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/admin/productManagerServlet")
@MultipartConfig
public class ProductManagerServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(ProductManagerServlet.class.getName());
    private final GoodsDao goodsDao = new GoodsDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String action = request.getParameter("action");

        try {
            switch (action) {
                case "updateProduct":
                    handleUpdateProduct(request, response);
                    break;
                case "uploadImage":
                    handleUploadImage(request, response);
                    break;
                default:
                    sendError(response, "无效的操作");
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error in ProductManagerServlet", e);
            sendError(response, "操作失败：" + e.getMessage());
        }
    }

    private void handleUpdateProduct(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int productId = Integer.parseInt(request.getParameter("productId"));
        Optional<Goods> goodsOpt = goodsDao.getGoodsById(productId);

        if (goodsOpt.isPresent()) {
            Goods goods = goodsOpt.get();
            goods.setName(request.getParameter("name"));
            goods.setPrice(Double.parseDouble(request.getParameter("price")));
            goods.setStock(Integer.parseInt(request.getParameter("stock")));
            goods.setDescription(request.getParameter("description"));

            if (goodsDao.updateGoods(goods)) {
                sendSuccess(response);
            } else {
                sendError(response, "更新商品信息失败");
            }
        } else {
            sendError(response, "商品不存在");
        }
    }

    private void handleUploadImage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int productId = Integer.parseInt(request.getParameter("productId"));
        Part filePart = request.getPart("image");
        String contentType = filePart.getContentType();

        // 读取文件数据
        byte[] imageData;
        try (InputStream input = filePart.getInputStream()) {
            // Create a buffer
            byte[] buffer = new byte[8192];
            int bytesRead;
            java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();

            // Read the file in chunks
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            imageData = output.toByteArray();
        }

        // 转换为base64
        String base64Image = Base64.getEncoder().encodeToString(imageData);

        // 更新商品图片
        Optional<Goods> goodsOpt = goodsDao.getGoodsById(productId);
        if (goodsOpt.isPresent()) {
            Goods goods = goodsOpt.get();
            goods.setImageData(base64Image);
            goods.setImageType(contentType);

            if (goodsDao.updateGoods(goods)) {
                sendSuccess(response);
            } else {
                sendError(response, "更新商品图片失败");
            }
        } else {
            sendError(response, "商品不存在");
        }
    }

    private void sendSuccess(HttpServletResponse response) throws IOException {
        response.getWriter().write("{\"success\":true}");
    }

    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.getWriter().write("{\"success\":false,\"message\":\"" + message + "\"}");
    }
}
